from svn.remote import RemoteClient
import sys
import svn as s
from util.exception import ValidationError
import traceback
import pysvn
from django.conf import settings
import os
from collections import OrderedDict


class SvnPathTool:
    def __init__(self):
        self.username = settings.SVN_USERNAME
        self.password = settings.SVN_PASSWORD
        # self.username = username
        # self.password = password

    def __get_fist_level(self):
        file_dirs = []
        try:
            url = settings.SVN_HEAD
            svn = RemoteClient(url, username=self.username, password=self.password)
            file_dirs = svn.run_command(subcommand="list", args=[url])
        except Exception as e:
            pass
        return file_dirs

    def __get_else_level(self, file_dirs):
        data = {}
        for file_dir in file_dirs:
            data[file_dir] = []
            files = []
            try:
                url = "".join([settings.SVN_HEAD, "/", file_dir])
                svn = RemoteClient(url, username=self.username, password=self.password)
                files = svn.run_command(subcommand="list", args=[url])
            except:
                pass
            for file in files:
                if file.startswith("svn"):
                    continue
                if not file.endswith("/"):
                    data[file_dir].append({file: file})
                else:
                    data[file_dir].append(self.__get_else_level(file))

                data.update({
                    file_dir: files
                })
        return data

    def get_level(self, file_dir):
        datas = []
        try:
            url = "".join([settings.SVN_HEAD, file_dir])
            svn = RemoteClient(url, username=self.username, password=self.password)
            files = svn.run_command(subcommand="list", args=[url])
            if file_dir:
                file_name = file_dir.split("/")[-2]
                file_name = "{}/".format(file_name)
            else:
                file_name = ""
            for file in files:
                if file.startswith("svn"):
                    continue
                if not file.endswith("/"):
                    datas.append({file: file})
                else:
                    a = "{}{}".format(file_dir, file)
                    datas.append(self.get_level(a))
            return {file_name: datas}
        except Exception as e:
            return {}

    def get_dir_info(self):
        data = self.get_level("")
        return data

    def get_log(self, file_path):
        url = "".join([settings.SVN_HEAD, "/", file_path])
        svn = RemoteClient(url, username=self.username, password=self.password)
        logs = svn.run_command(subcommand="log", args=[url])
        cut_logs = []
        for i in logs:
            if i:
                if i.startswith("svn"):
                    continue
                elif i.startswith("---"):
                    continue
                else:
                    cut_logs.append(i)
        cuts = cut_logs[0].split("|")
        new_version = cuts[0]
        new_version = new_version.replace("r", "")
        new_version = new_version.replace(" ", "")
        return new_version

    def get_commit_msg(self, file_path):
        url = "".join([settings.SVN_HEAD, "/", file_path])
        svn = RemoteClient(url, username=self.username, password=self.password)
        logs = svn.run_command(subcommand="log", args=[url])
        cut_logs = []
        cut_logs = []
        for i in logs:
            if i:
                if i.startswith("svn"):
                    continue
                elif i.startswith("-"):
                    continue
                elif i.__contains__("|"):
                    continue
                else:
                    cut_logs.append(i)
        msg = cut_logs[0]
        print(msg)
        return msg


class SvnTool:
    def __init__(self, url, version=""):
        self.path = url
        self.version = version
        self.url = "".join([settings.SVN_HEAD, url])
        self.username = settings.SVN_USERNAME
        self.password = settings.SVN_PASSWORD
        self.svn = RemoteClient(self.url, username=self.username, password=self.password)
        self.che_d = None

    def __get_checkout_dir(self):
        dirs = self.path.split("/")
        dirs = dirs[:-1]
        svn_dir = "/".join(dirs)
        checkout_dir = settings.VERSION_PATH.format(svn_dir)
        if not os.path.isdir(checkout_dir):
            os.makedirs(checkout_dir, exist_ok=True)
        self.che_d = checkout_dir
        return checkout_dir

    def get_origin_file(self):
        try:
            checkout_dir = self.__get_checkout_dir()
            self.svn.export(checkout_dir, revision=self.version, force=True)
            return True
        except:
            return False


class SvnExport:
    def __init__(self, url, path, version):
        self.path = url
        self.file_path = path
        self.version = version
        self.url = "".join([settings.SVN_HEAD, url])
        self.username = settings.SVN_USERNAME
        self.password = settings.SVN_PASSWORD
        self.svn = RemoteClient(self.url, username=self.username, password=self.password)
        self.che_d = None

    def __get_checkout_dir(self):
        checkout_dir = self.file_path
        if not os.path.isdir(checkout_dir):
            os.makedirs(checkout_dir, exist_ok=True)
        self.che_d = checkout_dir
        return checkout_dir

    def get_origin_file(self):
        checkout_dir = self.__get_checkout_dir()
        self.svn.export(checkout_dir, revision=self.version, force=True)


if __name__ == '__main__':
    s = SvnPathTool()
    a = s.get_level("trunk/")
